package com.pearlsoft.webapp.sysmgr.userRole;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.pearlsoft.commons.utils.UUIDUtil;
import com.pearlsoft.webapp.core.annotation.QueryHandlerComponent;
import com.pearlsoft.webapp.core.dataset.DataSet;
import com.pearlsoft.webapp.core.dataset.Query;
import com.pearlsoft.webapp.core.dataset.spi.ContextQueryHandler;
import com.pearlsoft.webapp.core.web.session.SessionProfile;
import com.pearlsoft.webapp.core.web.util.HttpUtil;


/**
 * 
 * @author YEHH
 *
 */
@QueryHandlerComponent(name = "SysUserRoleLoadHandler")
public class SysUserRoleLoadHandler extends ContextQueryHandler {

	public void handler(Query query, DataSet ds) throws Exception {
		
	}
	
	
	/**
	 * 查询用户分配的角色
	 * @param query
	 * @param ds
	 * @throws Exception
	 */
	public void queryUserRole(Query query, DataSet ds) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String id = (String) query.get("USER_ID");
		String sql = "SELECT A.USER_ROLE_ID,B.* FROM SYS_USER_ROLE A LEFT JOIN SYS_ROLE B ON A.ROLE_ID = B.ROLE_ID  WHERE A.USER_ID=?  ";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[] {id });
		for (Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext();) {
			Map<String, Object> map = iter.next();
			ds.newRecord();
			Iterator<?> _iterMap = map.entrySet().iterator();
			while(_iterMap.hasNext()){
				 Map.Entry<String,?> entry = (Map.Entry) _iterMap.next();
				 Object key = entry.getKey();
				 Object val = entry.getValue();
				ds.setValue(key.toString(), val);
			}
			
			
		}
		
	}
	
	
	/**
	 * 查询用户未分配的角色
	 * @param query
	 * @param ds
	 * @throws Exception
	 */
	public void queryUserRoleAssign (Query query, DataSet ds) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String id = (String) query.get("USER_ID");
		String sql ="SELECT A.* FROM SYS_ROLE A LEFT JOIN (SELECT * FROM SYS_USER_ROLE WHERE USER_ID=? ) B ON A.ROLE_ID = B.ROLE_ID WHERE B.ROLE_ID IS NULL ";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[] {id });
		for (Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext();) {
			Map<String, Object> map = iter.next();
			ds.newRecord();
			Iterator<?> _iterMap = map.entrySet().iterator();
			while(_iterMap.hasNext()){
				 Map.Entry<String,?> entry = (Map.Entry) _iterMap.next();
				 Object key = entry.getKey();
				 Object val = entry.getValue();
				ds.setValue(key.toString(), val);
			}
			
			
		}
	}
	
	
	public void queryUserMemu(Query query, DataSet ds) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String userId =HttpUtil.getCookieValueByName(getHttpServletRequest(), SessionProfile.COOKIE_USERID);
		String userCode = HttpUtil.getCookieValueByName(getHttpServletRequest(), SessionProfile.COOKIE_USERCODE);
		List<Map<String, Object>> list =  null;
		if(!userCode.equals(SessionProfile.ADMIN_CODE)){
			String sql = "SELECT * FROM (SELECT DISTINCT(C.MENU_ID) FROM (SELECT * FROM sys_user_role A WHERE A.USER_ID=?) B LEFT JOIN sys_role_menu C " +
			"ON B.ROLE_ID = C.ROLE_ID WHERE C.MENU_ID IS NOT NULL  ) D LEFT JOIN sys_menu F ON D.MENU_ID = F.MENU_ID where F.MENU_TYPE<>'0' ORDER BY F.MENU_PARENT_ID,F.MENU_ORDER";
			list = jdbcTemplate.queryForList(sql,new Object[] {userId});
		}else{
			String sql = "SELECT * FROM SYS_MENU WHERE MENU_TYPE<>'0' ORDER BY MENU_PARENT_ID,MENU_ORDER";
			list = jdbcTemplate.queryForList(sql);
		}
	
		Map<String,List<Map<String,Object>>>  smap = new HashMap<String,List<Map<String,Object>>>();
		for (Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext();) {
			Map<String, Object> _map = iter.next();
			
			List<Map<String,Object>> _list = smap.get(_map.get("MENU_PARENT_ID"));
			if(null ==_list){
				_list = new ArrayList<Map<String,Object>>();
			}
			Map<String, Object> _tmpMap = new HashMap<String, Object>();
			_tmpMap.put("id", _map.get("MENU_ID"));
			_tmpMap.put("parentId", _map.get("MENU_PARENT_ID"));
			_tmpMap.put("text", _map.get("MENU_NAME"));
			_tmpMap.put("qtip", _map.get("MENU_NAME"));
			_tmpMap.put("url", _map.get("MENU_URL"));
			_tmpMap.put("hrefTarget", _map.get("MENU_URL"));
			_tmpMap.put("icon", _map.get("MENU_IMG_CLS"));
			_list.add(_tmpMap);
			smap.put(_map.get("MENU_PARENT_ID").toString().trim(), _list);
		}
		List<Map<String, Object>> reList = smap.get("0");
		for(Iterator<Map<String, Object>> iter = reList.iterator(); iter.hasNext();){
			Map<String, Object> map =iter.next();
			this.doRecursion(smap,map);
		}
		reList.add(0, this.getUserUrl(userId));
		ds.newRecord();
		ObjectMapper objectMapper = new ObjectMapper();
		ds.setValue("tree",objectMapper.writeValueAsString(reList));
	}
	
	private void doRecursion(Map<String,List<Map<String,Object>>> smap,Map<String, Object> map){
		List<Map<String, Object>> aaList =  smap.get(map.get("id"));
		if(null!=aaList){
			map.put("children", aaList);
			for(Iterator<Map<String, Object>> iter = aaList.iterator(); iter.hasNext();){
				Map<String, Object> _map =iter.next();
				doRecursion(smap,_map);
			}
		} else {
		    map.put("leaf", "true");
		}
	}

	
	/**
	 * 返回用户自定义快捷菜单
	 * @return
	 */
	private  Map<String, Object> getUserUrl(String userId ) {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String sql  ="SELECT B.* FROM SYS_USER_URL  A LEFT JOIN SYS_MENU B ON A.MENU_ID=B.MENU_ID WHERE A.USER_ID=?";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[] {userId});
		List<Map<String,Object>> rList = new ArrayList<Map<String,Object>>();
		for (Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext();) {
			Map<String, Object> _map = iter.next();
			Map<String, Object> _tmpMap = new HashMap<String, Object>();
			_tmpMap.put("id", _map.get("MENU_ID"));
			_tmpMap.put("parentId", _map.get("MENU_PARENT_ID"));
			_tmpMap.put("text", _map.get("MENU_NAME"));
			_tmpMap.put("qtip", _map.get("MENU_NAME"));
			_tmpMap.put("url", _map.get("MENU_URL"));
			_tmpMap.put("hrefTarget", _map.get("MENU_URL"));
			_tmpMap.put("icon", _map.get("MENU_IMG_CLS"));
			_tmpMap.put("leaf", "true");
			rList.add(_tmpMap);
		}
		
		Map<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("id", UUIDUtil.get());
		rMap.put("parentId", "0");
		rMap.put("text", "个人工作台");
		rMap.put("qtip", "个人工作台");
		rMap.put("url", "");
		rMap.put("hrefTarget", "");
		rMap.put("icon","");
		rMap.put("children", rList);
		return rMap;
		
	}
}
